<?php
/*****************************************************
 * File name: LolApi.php
 * Create date: 2019/03/28
 * Author: liuyue
 * Description: Api接口模块cgi
 *****************************************************/

namespace Ctrl;

use Lib;
use Lib\Service\JsonService;
use Lib\Paas\Login;
use Model;

class LolApi extends Lib\Base\Ctrl
{

    private $db;
    private $savePath;
    private $baseUrl;
    private $jsSavePath;
    //图片输出处理
    private $baseIconPath = "https://game.gtimg.cn/images/lol/act/";
    //需要处理的图片字段
    private $imgKey = ['mainImg','iconImg','videoImg','sourceImg','loadingImg','abilityIconPath'];

    public function __construct()
    {
        //校验管理员权限
        $roleService = new Lib\Paas\Role();
        $checkAdmin = $roleService->getRoleInfo();
//        if ($checkAdmin['role'] != ROLE_ID) {
//            die('抱歉！您没有访问权限');
//        }
//        if (!in_array(MODULE_ID, $checkAdmin['moduleID']) ) {
//            die('抱歉！您没有访问权限');
//        }
        $this->db = Lib\Db\DbModel::init();
        //todo 环境判断
        if (ENV == 'test' && ENVIRONMENT == 'NON_OA') {
            $this->savePath = APP . 'upload/';
            //图片上传路径
            $this->baseUrl = 'upload/';
            //js文件的保存路径
            $this->jsSavePath = 'upload/js/';
        } else {
            $this->savePath = UPLOADED_PATH;
            //图片上传路径
            $this->baseUrl = IMG_BASE_URL;
            //js文件的保存路径
            $this->jsSavePath = DOWNLOAD_BASE_URL;
        }
    }

    public function changeImgUrl($imgPath)
    {
        //判断原来图片路径是否包含 https://game.gtimg.cn/images/lol/act/ 而且  /upload/ 或者 upload/ 开头
        if ((strpos($imgPath, '/upload/') === 0 || strpos($imgPath, 'upload/') === 0) && strpos($imgPath, $this->baseIconPath) === false) {
            //替换图片
            $imgPath = str_replace(['/upload/', 'upload/'], '', $imgPath);
            $imgPath = $this->baseIconPath . $imgPath;
        }
        return $imgPath;
    }

    /**
     * 创建json保存目录
     * @param $dir
     * @return bool|string
     */
    public function makeDir($dir)
    {
        $savePath = $this->savePath;
        //目录
        $dir = 'jsonFiles/' . $dir . '/';
        if (!is_dir($savePath . $dir)) {
            $res = mkdir($savePath . $dir, 0755, true);
            logWrite(parent::LOG_TYPE_OTHER, $res, '', '创建保存目录');
            if ($res) {
                return $dir;
            }
            return false;
        }
        return $dir;
    }

    /**
     * 创建图片保存目录
     * @param $dir
     * @return bool|string
     */
    public function makeImgDir($dir)
    {
        $savePath = APP . 'upload/';
        //目录
        $dir = 'img/' . $dir . '/';
        if (!is_dir($savePath . $dir)) {
            $res = mkdir($savePath . $dir, 0755, true);
            logWrite(parent::LOG_TYPE_OTHER, $res, '', '创建保存目录');
            if ($res) {
                return $dir;
            }
            return false;
        }
        return $dir;
    }

    /**
     * 创建js文件保存目录
     * @param $versionNumber
     * @return bool|string
     */
    public function makeJsDir($versionNumber)
    {
        $savePath = $this->jsSavePath;

        //目录
        $dir = $versionNumber . '/';
        if (!is_dir($savePath . $dir)) {
            $res = mkdir($savePath . $dir, 0755, true);
            logWrite(parent::LOG_TYPE_OTHER, $res, '', '创建保存目录');
            if ($res) {
                return $savePath . $dir;
            }
            return false;
        }
        return $savePath . $dir;
    }

    /**
     * 生成全部英雄js
     * @param null $version 版本信息
     * @param bool $type 返回数据类型
     * @return mixed
     */
    public function heroList($version = null, $type = false)
    {
        //获取当前版本号
        if (empty($version)) {
            $model = new Model\VersionModel();
            $version = $model->getCurrentVersion();
        }
        $versionNumber = $version['versionNumber'];

        //获取英雄数据
        $where['versionId'] = $version['id'];
        $where['isDelete'] = 0;
        $where['releasestatus'] = 1;        

        $field = "heroId,name,alias,title,roles,image,isWeekFree,attack,defense,magic,difficulty";
        $heroList = $this->db->table('tbhero')->where($where)->order('heroId', 'asc')->select($field);
        if(count($heroList) === 0){
            $res['type'] = 0;
            logWrite(5, false, '', '生成的hero_list.js文件,没有英雄数据');
        }else{
            //创建目录
            $dir = $this->makeJsDir($versionNumber."/heroList");
            if (empty($dir)) {
                $res['code'] = 1;
                $res['msg'] = "目录创建失败";
                if ($type) {
                    return $res;
                }
                $this->ajaxReturn($res);
            }
            //设置保存文件的名称
            $saveName = 'hero_list.js';

            foreach ($heroList as $k => $v) {
                foreach ($v as $kk => $vv) {
                    $heroList[$k][$kk] = outportFilter($vv);
                }
                $heroList[$k]['roles'] = unserialize($heroList[$k]['roles']);
                $heroList[$k]['image'] = unserialize($heroList[$k]['image']);
            }
            $data['hero'] = $heroList;
            $data['version'] = $versionNumber;
            $data['fileName'] = $saveName;
            $data['fileTime'] = date('Y-m-d H:i:s', time());
            $r = file_put_contents($dir . $saveName, json_encode($data));
            if ($r) {
                $res['code'] = 0;
                $res['msg'] = "js已经生成";
                $res['url'] =  "/" . $dir . $saveName;
                $res['fileName'] = $saveName;
                $res['fileTime'] = $data['fileTime'];
                logWrite(5, true, '', '生成hero_list.js');
//            保存redis
//            $redis = Lib\Base\Redis::init();
//            $val = $redis->set($versionNumber . "_hero_list", json_encode($data));
//            if ($val) {
//                logWrite(5, true, '', '生成' . $versionNumber . ',hero_list redis');
//            } else {
//                logWrite(5, false, '', '生成' . $versionNumber . ',hero_list redis');
//            }
            } else {
                $res['code'] = 1;
                $res['msg'] = "js文件生成失败";
                logWrite(5, false, '', '生成hero_list.js');
            }
        }
        if ($type) {
            return $res;
        }
        $this->ajaxReturn($res);
    }

    /**
     * 生成道具js
     * @param null $version 版本信息
     * @param bool $type 返回数据类型
     * @return mixed
     */
    public function itemsList($version = null, $type = false)
    {
        //获取当前版本号
        if (empty($version)) {
            $model = new Model\VersionModel();
            $version = $model->getCurrentVersion();
        }
        $versionNumber = $version['versionNumber'];

        //获取道具数据
        $where['versionId'] = $version['id'];
        $where['isHide'] = 0;
        $where['releasestatus'] = 1;

        //获取物品分类
        $itemtype = $this->db->table('tbitemtype')->where(array('parentId'=>0))->select('id,alias');
        $type = array();
        foreach($itemtype as $k=>$v){
            $type[$k]['header'] = $v['alias'];
            $type[$k]['tags'] = $this->db->table('tbitemtype')->where(array('parentId'=>$v['id']))->select('alias');
        }
        $data['tree'] = $type;

        $field = "itemId,name,iconPath,price,description,maps,plaintext,sell,total,`into`,`from`,suitHeroId,tag,types";
        $itemList = $this->db->table('tbitems')->where($where)->order('itemId', 'asc')->select($field);
        if(count($itemList) === 0) {
            $res['type'] = 0;
            logWrite(5, false, '', '生成的items.js文件,没有道具数据');
        }else{
            //创建目录
            $dir = $this->makeJsDir($versionNumber."/items");
            if (empty($dir)) {
                $res['code'] = 1;
                $res['msg'] = "目录创建失败";
                if ($type) {
                    return $res;
                }
                $this->ajaxReturn($res);
            }
            //设置保存文件的名称
            $saveName = 'items.js';
            foreach ($itemList as $k => $v) {
                foreach ($v as $kk => $vv) {
                    $itemList[$k][$kk] = outportFilter($vv);
                }
                //处理地图
                if($itemList[$k]['maps']){
                    $itemList[$k]['maps'] = unserialize($itemList[$k]['maps']);
                    //遍历
                    foreach ($itemList[$k]['maps'] as $key=>$val)
                    {
                        $itemList[$k]['maps'][$key] = getItemsMaps($val);
                    }
                }

                $itemList[$k]['into'] = $itemList[$k]['into'] ? unserialize($itemList[$k]['into']) : '';
                $itemList[$k]['from'] = $itemList[$k]['from'] ? unserialize($itemList[$k]['from']) : '';
                $itemList[$k]['types'] = $itemList[$k]['types'] ? unserialize($itemList[$k]['types']) : '';
                $itemList[$k]['suitHeroId'] = $itemList[$k]['suitHeroId'] ? unserialize($itemList[$k]['suitHeroId']) : '';
            }
            $data['items'] = $itemList;
            $data['version'] = $versionNumber;
            $data['fileName'] = $saveName;
            $data['fileTime'] = date('Y-m-d H:i:s', time());

            $r = file_put_contents($dir . $saveName, json_encode($data));
            if ($r) {
                $res['code'] = 0;
                $res['msg'] = "js已经生成";
                $res['url'] = "/" . $dir . $saveName;
                $res['fileName'] = $saveName;
                $res['fileTime'] = $data['fileTime'];
                logWrite(5, true, '', '生成items.js');
                //保存redis
//            $redis = Lib\Base\Redis::init();
//            $val = $redis->set($versionNumber . "_item_list", json_encode($data));
//            if ($val) {
//                logWrite(5, true, '', '生成' . $versionNumber . ',items redis');
//            } else {
//                logWrite(5, false, '', '生成' . $versionNumber . ',items redis');
//            }
            } else {
                $res['code'] = 1;
                $res['msg'] = "js文件生成失败";
                logWrite(5, false, '', '生成items.js');
            }
        }
        if ($type) {
            return $res;
        }
        $this->ajaxReturn($res);
    }

    /**
     * 生成皮肤js
     * @param null $version 版本信息
     * @param bool $type 返回数据类型
     * @return mixed
     */
    public function skinsList($version = null, $type = false)
    {
        //获取当前版本号
        if (empty($version)) {
            $model = new Model\VersionModel();
            $version = $model->getCurrentVersion();
        }
        $versionNumber = $version['versionNumber'];

        //获取英雄数据
        $where['versionId'] = $version['id'];
        $where['isDelete'] = 0;
        $where['releasestatus'] = 1;

        $field = "skinId,heroId,heroName,heroTitle,name,chromas,chromasBelongId,isBase,emblemsName,description,mainImg,iconImg,loadingImg,videoImg,sourceImg,vedioPath,suitType,publishTime";
        $skinList = $this->db->table('tbskins')->where($where)->order('skinId', 'asc')->select($field);
        if(count($skinList) === 0) {
            $res['type'] = 0;
            logWrite(5, false, '', '生成的skins.js文件,没有英雄皮肤数据');
        }else{
            //创建目录
            $dir = $this->makeJsDir($versionNumber."/skins");
            if (empty($dir)) {
                $res['code'] = 1;
                $res['msg'] = "目录创建失败";
                if ($type) {
                    return $res;
                }
                $this->ajaxReturn($res);
            }
            //设置保存文件的名称
            $saveName = 'skins.js';
            foreach ($skinList as $k => $v) {
                foreach ($v as $kk => $vv) {
                    $skinList[$k][$kk] = outportFilter($vv);
                    //处理皮肤图片
                    if(in_array($kk,$this->imgKey)){
                        $skinList[$k][$kk] = $this->changeImgUrl($skinList[$k][$kk]);
                    }
                }
            }
            $data['skins'] = $skinList;
            $data['version'] = $versionNumber;
            $data['fileName'] = $saveName;
            $data['fileTime'] = date('Y-m-d H:i:s', time());
            $r = file_put_contents($dir . $saveName, json_encode($data));
            if ($r) {
                $res['code'] = 0;
                $res['msg'] = "js已经生成";
                $res['url'] = "/" . $dir . $saveName;
                $res['fileName'] = $saveName;
                $res['fileTime'] = $data['fileTime'];
                logWrite(5, true, '', '生成skins.js');
//            保存redis
//            $redis = Lib\Base\Redis::init();
//            $val = $redis->set($versionNumber . "_skins_list", json_encode($data));
//            if ($val) {
//                logWrite(5, true, '', '生成' . $versionNumber . ',skins redis');
//            } else {
//                logWrite(5, false, '', '生成' . $versionNumber . ',skins redis');
//            }
            } else {
                $res['code'] = 1;
                $res['msg'] = "js文件生成失败";
                logWrite(5, false, '', '生成skins.js');
            }
        }
        if ($type) {
            return $res;
        }
        $this->ajaxReturn($res);
    }

    /**
     * 生成英雄js
     * @param int $heroId
     * @param null $version 版本信息
     * @param bool $type 返回数据类型
     * @return mixed
     */
    public function hero($heroId = 0, $version = null, $type = false)
    {
        //获取当前版本号
        if (empty($version)) {
            $model = new Model\VersionModel();
            $version = $model->getCurrentVersion();
        }
        $versionNumber = $version['versionNumber'];
        if (empty($heroId)) {
            $heroId = I('heroId', 0, 'intval');
        }
        if (empty($heroId)) {
            $res['code'] = 1;
            $res['msg'] = "heroId 不能为空";
            if ($type) {
                return $res;
            }
            $this->ajaxReturn($res);
        }
        $dir = $this->makeJsDir($versionNumber . '/hero');
        if (empty($dir)) {
            $res['code'] = 1;
            $res['msg'] = "目录创建失败";
            if ($type) {
                return $res;
            }
            $this->ajaxReturn($res);
        }

        //设置保存文件的名称
        $saveName = $heroId . '.js';
        //获取英雄数据
        $where['versionId'] = $version['id'];
        $where['heroId'] = $heroId;
        $where['isDelete'] = 0;
        $where['releasestatus'] = 1;

        $heroField = "heroId,name,alias,title,roles,image,shortBio,camp,attack,defense,magic,difficulty,
        hp,hpperlevel,mp,mpperlevel,movespeed,armor,armorperlevel,spellblock,spellblockperlevel,attackrange,
        hpregen,hpregenperlevel,mpregen,mpregenperlevel,crit,critperlevel,attackdamage,attackdamageperlevel,
        attackspeed,attackspeedperlevel,allytips,enemytips,heroVideoPath,isWeekFree,
        damageType,style,difficultyL,damage,durability,crowdControl,mobility,utility";
        $hero = $this->db->table('tbhero')->where($where)->find($heroField);
        foreach ($hero as $k => $v) {
            $hero[$k] = outportFilter($v);
            if ($k == 'roles' || $k == 'image') {
                $hero[$k] = unserialize($hero[$k]);
            }
        }
        //修改英雄技巧换行问题
        $hero['allytips'] = explode('-',ltrim($hero['allytips'],'-'));
        foreach($hero['allytips'] as $k=>$v){
            $hero['allytips'][$k] = '-'.$v;
        }
        //获取英雄对应的皮肤数据
        $skinsField = "skinId,heroId,heroName,heroTitle,name,chromas,chromasBelongId,isBase,emblemsName,description,mainImg,iconImg,loadingImg,videoImg,sourceImg,vedioPath,suitType,publishTime";
        $skins = $this->db->table('tbskins')->where($where)->order('skinId', 'asc')->select($skinsField);
        foreach ($skins as $k => $v) {
            foreach ($v as $kk => $vv) {
                $skins[$k][$kk] = outportFilter($vv);
                //处理皮肤图片
                if(in_array($kk,$this->imgKey)){
                    $skins[$k][$kk] = $this->changeImgUrl($skins[$k][$kk]);
                }
            }
        }
        //获取英雄对应的技能数据
        unset($where['releasestatus']);
        $spellsField = "heroId,spellKey,name,description,abilityIconPath,abilityVideoPath,dynamicDescription,cost,costburn,cooldown,cooldownburn";
        $spells = $this->db->table('tbspells')->where($where)->order('spellKey', 'asc')->select($spellsField);
        foreach ($spells as $k => $v) {
            foreach ($v as $kk => $vv) {
                $spells[$k][$kk] = outportFilter($vv);
                //处理皮肤图片
                if(in_array($kk,$this->imgKey)){
                    $spells[$k][$kk] = $this->changeImgUrl($spells[$k][$kk]);
                }
            }
            $spells[$k]['cost'] = unserialize($spells[$k]['cost']);
            $spells[$k]['cooldown'] = unserialize($spells[$k]['cooldown']);

        }
        $data['hero'] = $hero;
        $data['skins'] = $skins;
        $data['spells'] = $spells;
        $data['version'] = $versionNumber;
        $data['fileName'] = $saveName;
        $data['fileTime'] = date('Y-m-d H:i:s', time());
        $r = file_put_contents($dir . $saveName, json_encode($data));
        if ($r) {
            $res['code'] = 0;
            $res['msg'] = "js已经生成";
            $res['url'] = "/" . $dir . $saveName;
            $res['fileName'] = $saveName;
            $res['fileTime'] = $data['fileTime'];
            logWrite(5, true, '', '生成' . $heroId . '.js');
//            保存redis
//            $redis = Lib\Base\Redis::init();
//            $val = $redis->set($versionNumber . "_hero_".$heroId, json_encode($data));
//            if ($val) {
//                logWrite(5, true, '', '生成' . $versionNumber . ',hero:'.$heroId.' redis');
//            } else {
//                logWrite(5, false, '', '生成' . $versionNumber . ',hero:'.$heroId.' redis');
//            }
        } else {
            $res['code'] = 1;
            $res['msg'] = "js文件生成失败";
            logWrite(5, false, '', '生成' . $heroId . '.js');
        }
        if ($type) {
            return $res;
        }
        $this->ajaxReturn($res);
    }

    //生成全部
    public function makeAllJs()
    {
        //实例化Login类
        $login = new Login();
        $model = new Model\VersionModel();
        $version = $model->getCurrentVersion();
        $name = $login->getLoginInfo()['name'];
        $flag = 0;

        $record = [];
        //生成全部英雄
        $res = $this->heroList($version, true);
        if(isset($res['type'])&&$res['type']==0) {
           $flag +=1;
        }else{
            if ($res['code'] === 1) {
                $res['msg'] = "生成全部英雄js文件失败";
                $this->ajaxReturn($res);
            }
            //成功的同时记录文件生成的时间
            $record['hero_list'] = [
                'fileName' => $res['fileName'],
                'url' => $res['url'],
                'fileTime' => $res['fileTime'],
                'version' => $version['versionNumber']
            ];

            //判断是否为空
            if(!empty($record['hero_list']))
            {
                //添加数据
                $save['filename'] = $record['hero_list']['fileName'];
                $save['url'] = $record['hero_list']['url'];
                $save['createtime'] = date("Y-m-d H:i:s", time());
                $save['versionId'] = $version['id'];
                $save['creater'] = $name;
                $res = $this->db->table('tbrecord')->insert($save);
                if(!$res){
                    $res['msg'] = "写入至tbRecord表失败";
                    $this->ajaxReturn($res);
                    //日志记录
                    logWrite(1, false, 'tbrecord', $record['hero_list']['fileName'].'写入至tbRecord表失败');
                }else{
                    $res['msg'] = "写入至tbRecord表成功";
                    //日志记录
                    logWrite(1, true, 'tbrecord', $record['hero_list']['fileName'].'写入至tbRecord表成功');
                }
            }
        }


        //生成道具
        $res = $this->itemsList($version, true);
        if(isset($res['type'])&&$res['type']==0) {
            $flag +=1;
        }else{
            if ($res['code'] === 1) {
                $res['msg'] = "生成道具js文件失败";
                $this->ajaxReturn($res);
            }
            //成功的同时记录文件生成的时间
            $record['items'] = [
                'fileName' => $res['fileName'],
                'url' => $res['url'],
                'fileTime' => $res['fileTime'],
                'version' => $version['versionNumber']
            ];

            //判断是否为空
            if(!empty($record['items']))
            {
                //添加数据
                $save['filename'] = $record['items']['fileName'];
                $save['url'] = $record['items']['url'];
                $save['createtime'] = date("Y-m-d H:i:s", time());
                $save['versionId'] =  $version['id'];
                $save['creater'] = $name;
                $res = $this->db->table('tbrecord')->insert($save);
                if(!$res){
                    $res['msg'] = "写入至tbRecord表失败";
                    $this->ajaxReturn($res);
                    //日志记录
                    logWrite(1, false, 'tbrecord',$record['items']['fileName'].'写入至tbRecord表失败');
                }else{
                    $res['msg'] = "写入至tbRecord表成功";
                    //日志记录
                    logWrite(1, true, 'tbrecord', $record['items']['fileName'].'写入至tbRecord表成功');
                }
            }
        }


        //生成皮肤
        $res = $this->skinsList($version, true);
        if(isset($res['type'])&&$res['type']==0) {
            $flag +=1;
        }else{
            if ($res['code'] === 1) {
                $res['msg'] = "生成皮肤js文件失败";
                $this->ajaxReturn($res);
            }

            //成功的同时记录文件生成的时间
            $record['skins'] = [
                'fileName' => $res['fileName'],
                'url' => $res['url'],
                'fileTime' => $res['fileTime'],
                'version' => $version['versionNumber']
            ];

            //判断是否为空
            if(!empty($record['skins']))
            {
                //添加数据
                $save['filename'] = $record['skins']['fileName'];
                $save['url'] = $record['skins']['url'];
                $save['createtime'] = date("Y-m-d H:i:s", time());
                $save['versionId'] =  $version['id'];
                $save['creater'] = $name;
                $res = $this->db->table('tbrecord')->insert($save);
                if(!$res){
                    $res['msg'] = "写入至tbRecord表失败";
                    $this->ajaxReturn($res);
                    //日志记录
                    logWrite(1, false, 'tbrecord', $record['skins']['fileName'].'写入至tbRecord表失败');
                }else{
                    $res['msg'] = "写入至tbRecord表成功";
                    //日志记录
                    logWrite(1, true, 'tbrecord', $record['skins']['fileName'].'写入至tbRecord表成功');
                }

            }
        }


        //获取全部英雄id
        $where['versionId'] = $version['id'];
        $where['isDelete'] = 0;
        $where['releasestatus'] = 1;

        $heroIds = $this->db->table('tbhero')->where($where)->order('heroId', 'asc')->select('heroId');
        if(count($heroIds) === 0) {
            $flag +=1;
            //日志记录
            logWrite(1, false, 'tbrecord','单个英雄写入至tbRecord表失败');
        }else{
            foreach ($heroIds as $k => $v) {
                $res = $this->hero($v, $version, true);
                if ($res['code'] === 1) {
                    $res['msg'] = "生成heroId:" . $v . "js文件失败";
                    $this->ajaxReturn($res);
                }
                //成功的同时记录文件生成的时间
                $record["hero_$v"] = [
                    'fileName' => $res['fileName'],
                    'url' => $res['url'],
                    'fileTime' => $res['fileTime'],
                    'version' => $version['versionNumber']
                ];

                //判断是否为空
                if(!empty($record["hero_$v"]))
                {
                    //添加数据
                    $save['filename'] = $record["hero_$v"]['fileName'];
                    $save['url'] = $record["hero_$v"]['url'];
                    $save['createtime'] = date("Y-m-d H:i:s", time());
                    $save['versionId'] =  $version['id'];
                    $save['creater'] = $name;
                    $res = $this->db->table('tbrecord')->insert($save);
                    if(!$res){
                        $res['msg'] = "写入至tbRecord表失败";
                        $this->ajaxReturn($res);
                        //日志记录
                        logWrite(1, false, 'tbrecord',$record["hero_$v"]['fileName'].'写入至tbRecord表失败');
                    }else{
                        $res['msg'] = "写入至tbRecord表成功";
                        //日志记录
                        logWrite(1, true, 'tbrecord', $record["hero_$v"]['fileName'].'写入至tbRecord表成功');
                    }
                }
            }
        }

        //生成文件时间记录
        if(!empty($record)){
            $dir = $this->jsSavePath;
            $dir.=$version['versionNumber']."/record/";
            if (!is_dir($dir)) {
                $res = mkdir($dir, 0755, true);
                logWrite(parent::LOG_TYPE_OTHER, $res, '', '创建保存目录');
            }
            $saveName = 'record.js';
            file_put_contents($dir .$saveName, json_encode($record));

            //            保存redis
//            $redis = Lib\Base\Redis::init();
//            $val = $redis->set($version['versionNumber'] . "_record", json_encode($record));
//            if ($val) {
//                logWrite(5, true, '', '生成record' . $version['versionNumber'] . ' redis');
//            } else {
//                logWrite(5, false, '', '生成record' . $version['versionNumber'] . ' redis');
//            }

        }

        //判断$flag
        if($flag === 4){
            $r['code'] = 1;
            $r['msg'] = '当前' . $version['versionNumber'].'版本,没有发布数据';
            logWrite(5, false, '', '生成全部js文件没有数据');
            $this->ajaxReturn($r);
        }
        $r['code'] = 0;
        $r['msg'] = "生成全部js成功,path:" . '/' . $this->jsSavePath . $version['versionNumber'];
        $r['path'] = $this->jsSavePath . $version['versionNumber'];
        logWrite(5, true, '', '生成全部js成功');
        $this->ajaxReturn($r);
    }

    /**
     * 上传TMOBA/JSON版本数据
     */
    public function uploadJson()
    {
        //临时存储目录
        $save_dir = I('get.save_dir');
        $dir = $this->makeDir($save_dir);
        if (empty($dir)) {
            $res = [
                'code' => 1,
                'msg' => "目录创建失败"
            ];
            $this->ajaxReturn($res, 'json');
        }
        recordAMSLog(__FILE__ . ',' . __LINE__ . ',' . var_export($_FILES["file"]["name"], true));
        recordAMSLog(__FILE__ . ',' . __LINE__ . ',' . "savePath:" . $dir . ",save_dir:" . $save_dir);

        if (empty($_FILES["file"]["name"])) {
            $res = [
                'code' => 1,
                'msg' => "请先选择需要导入的文件"
            ];
            //文件上传日志
            logWrite(parent::LOG_TYPE_JSON_UPLOAD, false, '', '请先选择需要导入的文件');
            $this->ajaxReturn($res, 'json');
        }


        $res = saveUploadedFile($dir);
        if ($res) {
            //比较差异
            $service = new JsonService(1, $this->savePath . $dir . $_FILES["file"]["name"]);
            //获取在线版本号
            $check = $service->getChangeNumByFile();

            $res['dir'] = $dir;
            if ($check['code'] == 404) {
                $res['code'] = 404;
                unlink($this->savePath . $dir . $_FILES["file"]["name"]);
                $res['msg'] = "格式错误已被删除";
                $res['change_msg'] = $check['change_msg'];
            } else {
                $res['code'] = 0;
                $res['msg'] = "上传成功";
                $res['change_msg'] = $check['change_msg'];
            }
            //文件上传日志
            logWrite(parent::LOG_TYPE_JSON_UPLOAD, true, '',
                '上传json文件:' . $dir . $_FILES["file"]["name"] . '/' . $_FILES["file"]["name"]);
            $this->ajaxReturn($res, 'json');
        } else {
            $res = [
                'code' => 1,
                'msg' => "上传失败"
            ];
            //文件上传日志
            logWrite(parent::LOG_TYPE_JSON_UPLOAD, false, '',
                '上传json文件:' . $dir . $_FILES["file"]["name"] . '/' . $_FILES["file"]["name"]);
            $this->ajaxReturn($res, 'json');
        }
    }

    /**
     * 检测目录是否有文件
     */
    public function checkFile()
    {
        $json_dir = I('post.json_dir');
        $savePath = $this->savePath;
        $dir = $savePath . $json_dir;
        $file = read_all_file($dir);
        if (count($file) > 0) {
            $res['code'] = 0;
            $res['msg'] = '文件夹不为空';
            $this->ajaxReturn($res);
        } else {
            $res['code'] = 1;
            $res['msg'] = '文件夹为空';
            $this->ajaxReturn($res);
        }
    }

    /**
     * 上传图片
     */
    public function uploadAllTypeImg()
    {
        $versionId = I('versionId', 0, 'intval');
        $table = I('table');
        $key = I('key');
        $color = I('color');
        $res['code'] = 1;
        if (empty($versionId) || empty($table) || empty($key)) {
            $res['msg'] = "基础参数缺失";
            $this->ajaxReturn($res);
        }
        $basedir = '';
        $where['versionId'] = $versionId;
        switch ($table) {
            case 'tbhero':
                $heroId = I('heroId', 0, 'intval');
                if (empty($heroId)) {
                    $res['msg'] = "heroId不能为空";
                    $this->ajaxReturn($res);
                }
                $where['heroId'] = $heroId;
                $basedir = 'hero/' . $key;
                break;
            case 'tbitems':
                $itemId = I('itemId', 0, 'intval');
                if (empty($itemId)) {
                    $res['msg'] = "itemId不能为空";
                    $this->ajaxReturn($res);
                }
                $where['itemId'] = $itemId;
                $basedir = 'item/' . $key;
                break;
            case 'tbskins':
                $skinId = I('skinId', 0, 'intval');
                if (empty($skinId)) {
                    $res['msg'] = "skinId不能为空";
                    $this->ajaxReturn($res);
                }
                $where['skinId'] = $skinId;
                if($color){
                    $basedir = "chroma";
                }elseif($key == "mainImg"){
                    $basedir = "skin";
                }elseif($key == "iconImg"){
                    $basedir = "champion";
                }elseif($key == "loadingImg"){
                    $basedir = "skinloading";
                }elseif($key == "videoImg"){
                    $basedir = "skinvideo";
                }else{
                    $basedir = $key;
                }
                break;
            case 'tbspells':
                $heroId = I('heroId', 0, 'intval');
                $spellKey = I('spellKey');
                if (empty($spellKey) || empty($heroId)) {
                    $res['msg'] = "参数缺失";
                    $this->ajaxReturn($res);
                }
                $where['spellKey'] = $spellKey;
                $where['heroId'] = $heroId;
                $basedir = 'spells/' . $key;
                break;
            default:
                $res['msg'] = "table 不存在";
                $this->ajaxReturn($res);
                break;
        }

        //目录
        $imgname = $_FILES["file"]["name"];

        if (empty($imgname)) {
            $res['msg'] = "请先选择需要导入的图片";
            //文件上传日志
            logWrite(parent::LOG_TYPE_JSON_UPLOAD, false, '', '请先选择需要导入的文件');
            $this->ajaxReturn($res);
        }

        $dir = $this->makeImgDir($basedir);

        if (empty($dir)) {
            $res['code'] = "目录创建失败";
            $this->ajaxReturn($res, 'json');
        }

        recordAMSLog(__FILE__ . ',' . __LINE__ . ',' . var_export($imgname, true));
        recordAMSLog(__FILE__ . ',' . __LINE__ . ',' . "savePath:" . $dir . ",save_dir:" . $basedir);

        $r = saveUploadedFile($dir);
        if ($r) {
            //上传成功
            $path = $this->baseUrl . $dir . $imgname;
            $login = new Login();
            $save['updateMan'] = $login->getLoginInfo()['name'];
            $save['updateTime'] = date("Y-m-d H:i:s", time());
            $save[$key] = $path;
            $result = $this->db->table($table)->where($where)->update($save);
            logWrite(parent::LOG_TYPE_EDIT, $result, $table);
            if ($result) {
                //写入至tbrecord表里面去
                $data['filename'] = $imgname;
                $data['url'] = "/".$this->baseUrl . $dir . $imgname;
                $data['createtime'] = date('Y-m-d H:i:s',time());
                $data['versionId'] = $versionId;
                $data['creater'] = $login->getLoginInfo()['name'];
                $tbrecordRes = $this->db->table("tbrecord")->insert($data);
                if($tbrecordRes) {
                   //日志记录
                   logWrite(5,true,'tbrecord',"上传".$imgname."成功");
                }else{
                    //日志记录
                    logWrite(5,false,'tbrecord',"上传".$imgname."失败");
                }
                $res['code'] = 0;
                $res['msg'] = "上传成功";
                $res['url'] = $path;
                $this->ajaxReturn($res);
            } else {
                //同时删除文件
                deleteDir(APP.$this->baseUrl . $dir);
                $res['msg'] = "写入数据库失败";
                $this->ajaxReturn($res);
            }
        } else {
            $res['msg'] = "上传失败";
            logWrite(parent::LOG_TYPE_JSON_UPLOAD, false, $table, $dir . $imgname . '图片保存失败');
            $this->ajaxReturn($res);
        }
    }

    /**
     * 上传图片
     */
    public function uploadImg()
    {

        //实例化Login类
        $login = new Login();

        $id = I('post.id', '', 'trim');
        $type= I('post.type', '', 'trim');


        //目录
        $dir = $this->makeImgDir($type);

        if (empty($dir)) {
            $res = [
                'type' => 0,
                'msg' => "目录创建失败"
            ];
            $this->ajaxReturn($res, 'json');
        }
        $info = saveUploadedFile($dir);
        $loginInfo = $login->getLoginInfo()['name'];

        //获取当前版本
        $version = $this->db->table('tbversion')->where(['isCurrent' => 1])->find('id');
        $season  = $this->db->table('tbseason')->where(['isCurrent' => 1])->find('id');

        //如果上传
        if ($info) {
            //写入至tbrecord表里面去
            $data['filename'] = $_FILES['file']['name'];
            $data['url'] = "/".$this->baseUrl . $dir . $_FILES['file']['name'];
            $data['createtime'] = date('Y-m-d H:i:s',time());
            $data['versionId'] = $version['id'].'-'.$season['id'];//把版本和季度合并;
            $data['creater'] = $login->getLoginInfo()['name'];
            $tbrecordRes = $this->db->table("tbrecord")->insert($data);
            if($tbrecordRes) {
                //日志记录
                logWrite(5,true,'tbrecord',"上传".$_FILES['file']['name']."成功");
            }else{
                //日志记录
                logWrite(5,false,'tbrecord',"上传".$_FILES['file']['name']."失败");
            }

            $res = [
                'type' => 1,
                'msg' => '上传成功',
                'imagePath' => "upload/" . $dir . $_FILES['file']['name'],
            ];
            $this->ajaxReturn($res, 'json');
        } else {
            $res = [
                'type' => 0,
                'msg' => "上传失败"
            ];
            $this->ajaxReturn($res, 'json');
        }
    }

}